'use strict';
exports.html={
	begin:'<html><head><META HTTP-EQUIV="Content-Type" Content="text-html; charset=utf-8"></head><body>',
	end:'</body></html>'
};

exports.checkDate = function(dateStr){
    let dateFormat =/^(\d{4})-(\d{2})-(\d{2})$/;
    // 判断是否为yyyy-mm-dd格式的日期字符串
    if (dateFormat.test(dateStr)) {
        // 提取年月日
        if(!dateStr){
            return null;
        }
        let dateArr = dateStr.split('-');
        let year = parseInt(dateArr[0]);
        let month;           
        if(dateArr[1].indexOf("0") == 0){
            month = parseInt(dateArr[1].substring(1));
        }else{
            month = parseInt(dateArr[1]);
        }
        let day = parseInt(dateArr[2]);
        let new_date = new Date(year,month -1,day);
        
        // 判断日期合法性
        if (year === new_date.getFullYear() && month === new_date.getMonth()+1 && day === new_date.getDate()) {
            // 全部相等，被校验日期合法
            return true;
        } else {
            // 不全部相等，被校验日期的年、月、日至少有一个错误。
            return false;
        }

    } else {
        return false;
    }
}

exports.dateToString = function(DateIn) {
	// date -> string
	let Year=0;
	let Month=0;
	let Day=0;

	let CurrentDate="";

	//初始化时间
	Year = DateIn.getFullYear();
	Month = DateIn.getMonth()+1;
	Day = DateIn.getDate();

	CurrentDate = Year + "-";
	if (Month >= 10 ) {
		CurrentDate = CurrentDate + Month + "-";
	} else {
		CurrentDate = CurrentDate + "0" + Month + "-";
	}
	if (Day >= 10 ) {
		CurrentDate = CurrentDate + Day ;
	} else {
		CurrentDate = CurrentDate + "0" + Day ;
	}

	return CurrentDate;
}

exports.stringToDate = function(dateStr) {
	// string -> date
	let separator="-";
    var converted = Date.parse(dateStr);  
    var myDate = new Date(converted);  
    if (isNaN(myDate)){   
        var arys= dateStr.split(separator);  
        myDate = new Date(arys[0],arys[1]-1,arys[2]);
    }  
    return myDate;
}

exports.addDate = function(date, days, months, years) {
	// 在date上增加days天 months月 years年
	let temp = new Date(date);
	temp.setFullYear(temp.getFullYear() + years);
	temp.setMonth(temp.getMonth() + 1 + months);
	temp.setDate(temp.getDate() + days);
	return temp;
}
